<?php

namespace App\Modules\Common;


use App\Library\Rank\AbstractSingleRank;
use App\Modules\Order\Models\Order;
use App\Modules\Rebate\Models\Rebate;
use App\Modules\User\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class LowerSalesRank extends AbstractSingleRank
{
    protected static $key = "lower:sales";

    public static function setKey($prefix)
    {
        self::$key = "lower:sales:{$prefix}";
    }

    public static function flush()
    {
        $keys = Redis::keys("lower:sales*");
        if (!is_null($keys)) {
            foreach ($keys as $value) {
                Redis::del(mb_substr($value, 10));
            }
        }
    }

    public static function refresh()
    {
        static::flush();
        self::multi(function () {
            User::query()
                ->where('level', 3)
                ->orderBy('id', 'desc')
                ->each(function ($item) {
                    $user = $item->getTeam();
                    self::setKey("quarterly:".$item->id);
                    $orders = Order::query()
                        ->where('created_at', '>', now()->startOfQuarter()->toDateTimeString())
                        ->whereIn('referrer_id', $user->pluck('id')->all())
                        ->where('personal_id', $item->id)
                        ->where('referrer_level', 2)
                        ->where('status', Order::STATUS_PAID)
                        ->selectRaw('referrer_id, sum(original_price) as price')
                        ->groupBy('referrer_id')
                        ->get()
                        ->keyBy('referrer_id');
                    $user->each(function ($item2) use ($orders, $item) {
                        $order = $orders->get($item2->id);
                        self::update($item2->id, $order->price??0);
                    });
                    self::setKey("annual:".$item->id);
                    $orders = Order::query()
                        ->where('created_at', '>', now()->startOfYear()->toDateTimeString())
                        ->whereIn('referrer_id', $user->pluck('id')->all())
                        ->where('personal_id', $item->id)
                        ->where('referrer_level', 2)
                        ->where('status', Order::STATUS_PAID)
                        ->selectRaw('referrer_id, sum(original_price) as price')
                        ->groupBy('referrer_id')
                        ->get()
                        ->keyBy('referrer_id');
                        $user->each(function ($item2) use ($orders) {
                            $order = $orders->get($item2->id);
                            self::update($item2->id, $order->price??0);
                        });
                });
        });
    }
}
